<template>
  <div class="classify-container">
    <el-table
      row-key="id"
      :data="tableData"
      style="width: 100%"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="分类名称" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <div class="operation-buttons">
            <el-tooltip content="新增子分类" placement="top">
              <el-button
                class="operation-button"
                type="primary"
                link
                :icon="Plus"
                @click="handleAdd(scope.row)"
              />
            </el-tooltip>
            <el-tooltip content="修改分类" placement="top">
              <el-button
                class="operation-button"
                type="warning"
                link
                :icon="Edit"
                @click="handleEdit(scope.row)"
              />
            </el-tooltip>
            <el-tooltip content="删除分类" placement="top">
              <el-button
                class="operation-button"
                type="danger"
                link
                :icon="Delete"
                @click="handleDelete(scope.row)"
              />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ClassifyApi, type ClassifyItem } from '@/api/lession/classify'

interface TreeClassifyItem extends ClassifyItem {
  children?: TreeClassifyItem[]
}

const tableData = ref<TreeClassifyItem[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加分类')
const formRef = ref<FormInstance>()
const currentParent = ref<TreeClassifyItem | null>(null)

const formData = reactive({
  id: '',
  name: '',
  parentId: ''
})

const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
}

// 将扁平数组转换为树形结构
const convertToTree = (items: ClassifyItem[]): TreeClassifyItem[] => {
  const result: TreeClassifyItem[] = []
  const itemMap = new Map<number, TreeClassifyItem>()

  // 先转换成Map便于查找
  items.forEach(item => {
    const treeNode: TreeClassifyItem = {
      id: item.id,
      name: item.name,
      parentId: item.parentId,
      children: []
    }
    itemMap.set(item.id, treeNode)
  })

  // 构建树形结构
  itemMap.forEach((item) => {
    if (item.parentId) {
      const parent = itemMap.get(item.parentId)
      if (parent && parent.children) {
        parent.children.push(item)
      }
    } else {
      result.push(item)
    }
  })

  // 清理空的children数组
  const cleanEmptyChildren = (nodes: TreeClassifyItem[]) => {
    nodes.forEach(node => {
      if (node.children && node.children.length === 0) {
        delete node.children
      } else if (node.children) {
        cleanEmptyChildren(node.children)
      }
    })
  }
  cleanEmptyChildren(result)

  return result
}

// 获取列表数据
const getList = async () => {
  try {
    const res = await ClassifyApi.getClassifyList({ type: 1 })
    if (res) {
      tableData.value = convertToTree(res)
    }
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  }
}

// 添加按钮
const handleAdd = (row: TreeClassifyItem) => {
  dialogTitle.value = '添加分类'
  dialogVisible.value = true
  formData.id = ''
  formData.name = ''
  formData.parentId = row?.id?.toString() || ''
  currentParent.value = row || null
}

// 编辑按钮
const handleEdit = (row: TreeClassifyItem) => {
  dialogTitle.value = '编辑分类'
  dialogVisible.value = true
  formData.id = row.id.toString()
  formData.name = row.name
  formData.parentId = row.parentId?.toString() || ''
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      const submitData = {
        name: formData.name,
        type: 1,
        parentId: formData.parentId ? parseInt(formData.parentId) : null
      }

      if (formData.id) {
        await ClassifyApi.updateClassify({
          ...submitData,
          id: parseInt(formData.id)
        })
        ElMessage.success('更新成功')
      } else {
        await ClassifyApi.createClassify(submitData)
        ElMessage.success('添加成功')
      }
      dialogVisible.value = false
      getList()
    }
  })
}

// 删除按钮
const handleDelete = async (row: TreeClassifyItem) => {
  try {
    // 检查是否有子节点
    if (row.children) {
      ElMessage.warning('该分类下有子分类，不能删除')
      return
    }

    // 检查是否为根节点
    if (!row.parentId) {
      ElMessage.warning('根节点不能删除')
      return
    }

    await ElMessageBox.confirm('确认删除该分类吗?', '提示', {
      type: 'warning'
    })
    await ClassifyApi.deleteClassify(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 关闭对话框
const handleDialogClose = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  currentParent.value = null
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.classify-container {
  padding: 20px;

  .operation-buttons {
    display: flex;
    justify-content: center;
    gap: 8px;

    .operation-button {
      font-size: 18px;
      &:hover {
        transform: scale(1.1);
        transition: transform 0.2s;
      }
    }
  }
}
</style>
